package com.jrx.anytxn.param.job.bactchBillCompare.config;

import com.jrx.anytxn.param.config.AnytxnBatchProperties;
import com.jrx.anytxn.param.config.PathFileConfig;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.entity.TlBillTransCompareDetail;
import com.jrx.anytxn.param.entity.TlBillTransDetil;
import com.jrx.anytxn.param.job.bactchBillCompare.step.BillDetailUnmatchedListener;
import com.jrx.anytxn.param.job.bactchBillCompare.step.BillDetailUnmatchedProcessor;
import com.jrx.anytxn.param.job.bactchBillCompare.step.BillDetailUnmatchedWriter;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.batch.MyBatisCursorItemReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.support.SynchronizedItemStreamReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.SimpleAsyncTaskExecutor;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 核心对账-将未能匹配到txn交易记录的账务明细写入对账明细表job
 *
 * @author : zcc
 * 2020/11/26
 */
@Configuration
@EnableConfigurationProperties(PathFileConfig.class)
public class BatchBillDetailUnmatchedConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(BatchBillDetailUnmatchedConfiguration.class);

    @Resource(name = "paramSqlSessionFactory")
    SqlSessionFactory sqlSessionFactory;
    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    @Autowired
    private AnytxnBatchProperties anytxnBatchProperties;
    @Autowired
    private BillDetailUnmatchedProcessor billDetailUnmatchedProcessor;
    @Autowired
    private BillDetailUnmatchedWriter billDetailUnmatchedWriter;
    @Autowired
    private BillDetailUnmatchedListener billDetailUnmatchedListener;
    @Autowired
    private IOrganizationTableService organizationTableService;


    @Bean
    public Job billDetailUnmatchedJob() throws IOException {
        return jobBuilderFactory.get("billDetailUnmatchedJob").incrementer(new RunIdIncrementer()).listener(billDetailUnmatchedListener)
                .start(billDetailUnmatchedStep()) //将未能匹配到txn交易记录的账务明细写入对账明细表
                .build();
    }

    @Bean
    public Step billDetailUnmatchedStep(){
        return stepBuilderFactory.get("billDetailUnmatchedStep")
                .<TlBillTransDetil, TlBillTransCompareDetail>chunk(anytxnBatchProperties.getBatchBillCompareConfiguration().getChunkLimit())
                //表示一批处理100
                // 条记录，数据是逐条发送给processor处理的，处理100条记录后，统一返回给writer进行保存处理
                .reader(billDetailUnmatchedReader())
                .processor(billDetailUnmatchedProcessor)
                .writer(billDetailUnmatchedWriter)
                .taskExecutor(new SimpleAsyncTaskExecutor())
                .throttleLimit(anytxnBatchProperties.getBatchBillCompareConfiguration().getThrottleLimit())//多线程*/
                .build();
    }

    @Bean
    @StepScope
    public SynchronizedItemStreamReader<TlBillTransDetil> billDetailUnmatchedReader() {
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
        MyBatisCursorItemReader<TlBillTransDetil> cursorItemReader = new MyBatisCursorItemReader<>();
        cursorItemReader.setSaveState(false);
        cursorItemReader.setSqlSessionFactory(sqlSessionFactory);
        cursorItemReader.setQueryId("com.jrx.anytxn.param.mapper.ext.ExtTlBillTransDetilMapper.selectByTenIdAndBusDateAndComFlag");
        Map<String, Object> map = new HashMap<>();
        map.put("tenantId", org.getTenantId());
        map.put("businessDate", org.getToday());
        map.put("compareFlag", Constant.COMPARE_FLAG_0);
        cursorItemReader.setParameterValues(map);

        SynchronizedItemStreamReader<TlBillTransDetil> synchronizedItemStreamReader = new SynchronizedItemStreamReader<>();
        synchronizedItemStreamReader.setDelegate(cursorItemReader);
        return synchronizedItemStreamReader;
    }

}